package com.kzhkwkt.sugoieditor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class FileList extends Activity implements OnItemClickListener {
	private static final String TAG = "FIleList";
	private Data data = null;
	private final ArrayList<HashMap<String, String>> titles = new ArrayList<HashMap<String, String>>();

	public static final String FILE_ID_KEY = "FILE_ID_KEY";
	public static final String ACTIVE_FILE = "ACTIVE_FILE";

	ListView list = null;

    @Override
	public void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "onCreate in");
		super.onCreate(savedInstanceState);
		setTitle(getString(R.string.open_dialog_title));
		setContentView(R.layout.file_list);

		data = Data.getInstance(this);

		list = (ListView)findViewById(R.id.file_list_view);
		list.setOnItemClickListener(this);
		Log.i(TAG, "onCreate out");
	}

	@Override
	public void onStart() {
		Log.i(TAG, "onStart in");
		super.onStart();
		setAdapter();
		Log.i(TAG, "onStart out");
	}

	void setAdapter() {
		final HashMap<Integer, String> fileList = data.getList();
		if(fileList != null) {
			Iterator<Integer> itr = fileList.keySet().iterator();
			while(itr.hasNext()) {
				int id = itr.next();
				HashMap<String, String> file = new HashMap<String, String>();
				file.put(BaseColumns._ID, String.valueOf(id));
				file.put(Data.TITLE, fileList.get(id));
				titles.add(file);
			}
		}
		SimpleAdapter adapter = new SimpleAdapter(this, titles, R.layout.file_row, new String[]{BaseColumns._ID, Data.TITLE}, new int[]{R.id.file_id, R.id.title});
		list.setAdapter(adapter);
	}

	public void cancel(View v) {
		finish();
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Log.i(TAG, "onItemSelected in");
		TextView tv = (TextView)arg1.findViewById(R.id.file_id);
		Intent intent = new Intent();
		intent.putExtra(ACTIVE_FILE, getActiveFile(Integer.parseInt(tv.getText().toString())));
		setResult(C.ResponseCode.OPEN, intent);
		Log.i(TAG, "onItemSelected out");
		finish();
	}

	private ActiveFile getActiveFile(int id) {
		return data.getFileById(id);
	}

	public void onNothingSelected(AdapterView<?> arg0) {

	}
}